import signal
import signal
import sys
import threading

# from fastapi_amis_admin.amis import PageSchema
import uvicorn
from fastapi import FastAPI, File, UploadFile
from fastapi_amis_admin.admin import (
  AdminApp,
)
from fastapi_amis_admin.admin import admin
from fastapi_amis_admin.admin.settings import Settings
from fastapi_amis_admin.amis.components import PageSchema
from fastapi_user_auth.admin import AuthAdminSite
from loguru import logger
from sqlmodel import SQLModel  # 初始化数据库时运行一次（创建 auth_role 等表）

from biz.main_mgr import main_mgr
from models.table_defs import Category, Base
from utils.JsonResponse import JsonResponse
from utils.comm1 import SingletonMeta

app = FastAPI()
# site = AdminSite(settings=Settings(database_url_async='sqlite+aiosqlite:///maininfo.db'))
site = AuthAdminSite(settings=Settings(database_url_async='sqlite+aiosqlite:///maininfo.db'))
auth = site.auth

# @site.register_admin
# class CategoryAdmin(admin.ModelAdmin):
#     page_schema = '分类管理'
#     # 配置管理模型
#     model = Category

@site.register_admin
class BlogApp(admin.AdminApp):
  page_schema = PageSchema(label="博客应用", icon="fa fa-wordpress")
  router_prefix = "/blog"

  def __init__(self, app: "AdminApp"):
    super().__init__(app)
    self.register_admin(Category)


site.mount_app(app)

@app.on_event("startup")
async def startup():
    await site.db.async_run_sync(SQLModel.metadata.create_all, is_session=False) # 第一次运行时创建数据库表
    await site.db.async_run_sync(Base.metadata.create_all, is_session=False)
    if "auth" in globals():
      await init_auth(site.auth)


async def init_auth(auth):
  await auth.create_role_user("admin")
  # 创建默认超级管理员,用户名: root,密码: root, 请及时修改密码!!!
  await auth.create_role_user("root")
  # 运行site的startup方法,加载casbin策略等
  await site.router.startup()
  # 添加一条默认的casbin规则
  if not auth.enforcer.enforce("u:admin", site.unique_id, "page", "page"):
    await auth.enforcer.add_policy("u:admin", site.unique_id, "page", "page", "allow")

# @app.get("/auth/user")
# @auth.requires()
# def user(request: Request):
#     return request.user  # Current request user object.

class MgrFactory(metaclass=SingletonMeta):
  def __init__(self):
    self.mgr = main_mgr()
    self.main_task_thread = threading.Thread(target=self.mgr.start_task)

  def get_objs(self):
    return self.mgr, self.main_task_thread

def signal_handler(sig, frame):
  print('Received signal, stopping main_task_thread and exit...')
  main_mgr, main_task_thread = MgrFactory().get_objs()
  if main_mgr and main_task_thread:
    main_mgr.stop_task()
    main_task_thread.join()
  sys.exit(0)

def init_main_mgr_task():
  main_mgr, main_task_thread = MgrFactory().get_objs()
  main_task_thread.start()
  logger.info('main_mgr task thread started.')

@app.get("/")
async def root():
  return {"message": "Hello World"}

@app.post("/upload_paper_for_analyze/{act}")
async def upload_paper_for_analyze(act: str , file: UploadFile = File(...)):
  file_content = await file.read()
  main_mgr, main_task_thread = MgrFactory().get_objs()
  if not main_mgr:
    return JsonResponse.error( code=500,msg="main_mgr not found." )
  main_mgr.add_paper_analyze(file_content,file.filename,act)
  return JsonResponse.success(data={"filename": file.filename,  "act": act})

def my_init():
  signal.signal(signal.SIGINT, signal_handler)
  signal.signal(signal.SIGTERM, signal_handler)
  init_main_mgr_task()
  uvicorn.run(app, host="0.0.0.0", port=17028)
  # uvicorn.run('main:app', host="0.0.0.0", port=17028)


if __name__ == '__main__':
  my_init()

r"""
1. https://cloud.tencent.com/developer/article/2314968 : FastAPI 和 fastapi-amis-admin：强大而可扩展的后台管理解决方案！ , 包括： 用户认证及权限配置
2. https://www.cnblogs.com/liu-yao/p/14225921.html : FastAPI+fastapi-amis-admin 实现后台管理系统，实现增删改查功能，并集成文件上传下载功能。
"""